package com.es.hotel.main.client;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;

import java.io.IOException;
import java.util.List;

public class EsployClient {

    public static void Agg() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
   /*     将返回的文档数量设为 0。也就是说，这次查询不会返回任何实际的文档数据，
        只会返回一些元信息，如聚合结果或匹配的文档总数等。
        这通常用于只关心匹配的文档数量或进行聚合查询，而不需要实际的文档数据。*/
        request.source().size(0);
        //对brand进行聚合
        request.source().aggregation(
                AggregationBuilders.terms("brandAggregation").field("brand").size(20)
        );
        //解析结果
        SearchResponse response = EsIndexClient.client().search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = response.getAggregations();
        Terms brandAggregation = aggregations.get("brandAggregation");
        List<? extends Terms.Bucket> buckets = brandAggregation.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String brandName = bucket.getKeyAsString();
            System.out.println("brandName:" + brandName);
            long docCount = bucket.getDocCount();
            System.out.println("docCount:" + docCount);
        }
    }

    public static void main(String[] args) throws IOException {
        Agg();
    }
}
